'use client';

import { useEffect, useState } from 'react';
import { Table, Button, Card, Typography, Message, Spin, Badge, Space, Modal } from '@arco-design/web-react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { bookingApi } from '@/services/api';
import { Booking } from '@/types';
import { roomApi } from '@/services/api';
import { Room } from '@/types';
import { customerApi } from '@/services/api';
import { Customer } from '@/types';

const { Title } = Typography;

export default function AdminBookingsPage() {
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [loading, setLoading] = useState(true);
  const { userType, isAuthenticated } = useAuth();
  const router = useRouter();

  useEffect(() => {
    // 如果未登录或不是管理员，重定向到登录页
    if (!isAuthenticated) {
      router.push('/admin/login');
      return;
    }

    if (userType !== 'admin') {
      router.push('/');
      return;
    }

    fetchBookings();
  }, [isAuthenticated, userType, router]);

  const fetchBookings = async () => {
    setLoading(true);
    try {
      const response = await bookingApi.getAll();
      if (response.code === 200 && response.data) {
        // 兼容类型：将 customerId 映射为 customerID
        const bookings = response.data.map((item: any) => ({
          ...item,
          customerID: item.customerId,
        }));

        // 遍历预订列表，逐个获取房间和客户信息
        const bookingsWithDetails = await Promise.all(
          bookings.map(async (booking) => {
            // 并行发起房间和客户信息请求
            const [roomResponse, customerResponse] = await Promise.all([
              roomApi.getById(booking.roomId), // 获取房间信息
              customerApi.getById(booking.customerID) // 统一用 customerID
            ]);

            let roomInfo = undefined;
            if (roomResponse.code === 200 && roomResponse.data) {
              roomInfo = roomResponse.data;
            } else {
              console.error(`获取房间信息失败，预订ID: ${booking.bookingId}`, roomResponse);
            }

            let customerInfo = undefined;
            if (customerResponse.code === 200 && customerResponse.data) {
              customerInfo = customerResponse.data;
            } else {
              console.error(`获取客户信息失败，预订ID: ${booking.bookingId}`, customerResponse);
            }

            // 返回合并了房间和客户信息的新预订对象
            return { ...booking, roomInfo, customerInfo };
          })
        );

        setBookings(bookingsWithDetails);
      } else {
        // Message.error(response.message || '获取预订列表失败'); // 临时注释掉，避免渲染错误
        console.error('获取预订列表失败响应:', response);
      }
    } catch (error) {
      console.error('获取预订列表错误:', error);
      // Message.error('获取预订列表时发生错误'); // 临时注释掉，避免渲染错误
    } finally {
      setLoading(false);
    }
  };

  const handleCancelBooking = (bookingId: number) => {
    Modal.confirm({
      title: '取消预订',
      content: '确定要取消这个预订吗？此操作不可撤销。',
      okButtonProps: {
        status: 'danger',
      },
      onOk: async () => {
        try {
          const response = await bookingApi.cancel(bookingId);
          if (response.code === 200) {
            Message.success('预订已取消');
            fetchBookings(); // 刷新列表
          } else {
            // Message.error(response.message || '取消预订失败');
          }
        } catch (error) {
          console.error('取消预订错误:', error);
          // Message.error('取消预订时发生错误');
        }
      },
    });
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case '预订中':
        return <Badge status="processing" text="预订中" />;
      case '已入住':
        return <Badge status="success" text="已入住" />;
      case '已退房':
        return <Badge status="default" text="已退房" />;
      case '取消':
        return <Badge status="error" text="已取消" />;
      default:
        return <Badge status="default" text={status} />;
    }
  };

  const columns = [
    {
      title: '预订ID',
      dataIndex: 'bookingId',
      width: 80,
    },
    {
      title: '客户ID',
      dataIndex: 'customerId',
      width: 80,
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      width: 100,
      render: (_: any, record: Booking & { roomInfo?: Room, customerInfo?: Customer }) => record.customerInfo?.name || record.customerInfo?.username || '-',
    },
    {
      title: '房间号',
      dataIndex: 'roomNumber',
      width: 100,
      render: (_: any, record: Booking & { roomInfo?: Room }) => record.roomInfo?.roomNumber || '-',
    },
    {
      title: '房间类型',
      dataIndex: 'roomType',
      width: 120,
      render: (_: any, record: Booking & { roomInfo?: Room }) => record.roomInfo?.roomType || '-',
    },
    {
      title: '入住日期',
      dataIndex: 'checkInTime',
      width: 120,
      render: (text: string) => new Date(text).toLocaleDateString(),
    },
    {
      title: '退房日期',
      dataIndex: 'checkOutTime',
      width: 120,
      render: (text: string) => new Date(text).toLocaleDateString(),
    },
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      width: 100,
      render: (amount: number) => `¥${amount}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status: string) => getStatusBadge(status),
    },
    {
      title: '操作',
      width: 200,
      render: (_: any, record: Booking) => (
        <Space>
          {record.status === '预订中' && (
            <>
              <Button
                type="primary"
                size="small"
                onClick={() => router.push(`/admin/checkin?bookingId=${record.bookingId}`)}
              >
                办理入住
              </Button>
              <Button
                type="secondary"
                status="danger"
                size="small"
                onClick={() => handleCancelBooking(record.bookingId!)}
              >
                取消
              </Button>
            </>
          )}
          {record.status === '已入住' && (
            <Button
              type="primary"
              status="success"
              size="small"
              onClick={() => router.push(`/admin/checkin?bookingId=${record.bookingId}`)}
            >
              办理退房
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="py-6">
      <Card className="shadow-sm">
        <div className="flex justify-between items-center mb-6">
          <Title heading={3}>预订管理</Title>
          <Button
            type="primary"
            onClick={() => fetchBookings()}
          >
            刷新
          </Button>
        </div>

        {loading ? (
          <div className="flex justify-center py-12">
            <Spin />
          </div>
        ) : (
          <Table
            columns={columns}
            data={bookings}
            loading={loading}
            pagination={{
              pageSize: 10,
              showTotal: true,
            }}
            rowKey="bookingId"
            borderCell={true}
          />
        )}
      </Card>
    </div>
  );
}